package base;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class Test2 {
    private static final String ALGORITHM = "DES";
    private static final String TRANSFORMATION = "DES/ECB/PKCS5Padding"; // Java中使用PKCS5Padding实际上实现了PKCS7Padding的效果

    public static void main(String[] args) throws Exception {
        String text = "admin";
        String keyString = "h3c_api_key";

        // 加密
        String encryptedText = encrypt(text, keyString);
        System.out.println("Encrypted: " + encryptedText);
    }

    public static String encrypt(String plainText, String key) throws Exception {
        DESKeySpec desKeySpec = new DESKeySpec(key.getBytes(StandardCharsets.UTF_8));
        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(ALGORITHM);
        SecretKey secretKey = secretKeyFactory.generateSecret(desKeySpec);

        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);

        byte[] inputBytes = plainText.getBytes();
        byte[] outputBytes = cipher.doFinal(inputBytes);

        return Base64.getEncoder().encodeToString(outputBytes); // 使用Base64编码输出
    }
}
